package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;
import cn.com.kh.signUtil;
import cn.com.kh.AESUtil;

import org.json.JSONArray;
import org.json.JSONException;

import org.json.JSONObject;
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.parser.Feature;
/**
/**
 *
 * @Title: ApiBPEnum
 * @Description:深圳宝安排水小程序登录接口--外部接口
 * @author: chieh
 * @date 2020-11-08 21:28:00
 *
 */
public class ApiBPEnum implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(ApiBPEnum.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
		
		log.debug("-------------------------start ApiBPEnum 开始-----------------");
		
        long startTime = System.currentTimeMillis();
        String reJson = null;
        long endTime = 0;
		
		response.setContentType("application/json;charset=utf-8");
		
		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}
		
        try {
			
			// 调用处理信息
			//JSONObject inObject = JSONObject.parseObject(inData, Feature.OrderedField);
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());
			
			// usetype pid 排序问题
			JSONArray jsonArraytemp = new JSONArray(inObject.get("data").toString());
			log.debug("jsonArraytemp: " + jsonArraytemp);
			
			JSONObject dataObjecttemp = jsonArraytemp.getJSONObject(0);
			log.debug(dataObjecttemp);
			String usetypetemp = GetJV(dataObjecttemp, "usetype");
			String pidtemp = GetJV(dataObjecttemp, "pid");
			log.debug("usetype:"+usetypetemp+"	,pid:"+pidtemp);
			
			String replaceString ="[{\"usetype\":\""+usetypetemp+"\",\"pid\":\""+pidtemp+"\"}]";
			log.debug("replaceString:"+replaceString);
			
			//鉴权加密处理--验证密码
			JSONObject checkJson = signUtil.CheckSign(inObject,replaceString);
			log.debug("checkJson: " + checkJson);

			if (checkJson != null) {
				log.debug("[签名校验异常-返回信息]:" + checkJson);
				endTime = System.currentTimeMillis();
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败([签名校验异常-返回信息]:"+signUtil.jsonObjectToMap(checkJson)+"),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
				return reJson;
			} else {
				log.debug("[签名校验成功]");
				// 校验成功
				//todo 业务逻辑
			}
			//data获取参数openid
			JSONArray jsonArray = new JSONArray(inObject.get("data").toString());
			log.debug("jsonArray: " + jsonArray);
			def usetype= jsonArray.getJSONObject(0).get("usetype");
			def pid= jsonArray.getJSONObject(0).get("pid");
			
			log.debug("解析信息-usetype：" + usetype+"	pid："+pid);
			
            if (usetype == null) {
                endTime = System.currentTimeMillis();
                reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(参数输入异常),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                return reJson;
            }
			def sqlpart="";
			if(usetype=='A0001') {//单位类别
				sqlpart="select code_id+'|'+Code_Name as result from c_codetables  where Use_Type='单位类别'  and Use_Status=1 ORDER BY  OrderNo";
				
			}else if(usetype=='B0001') {//业务类型
				sqlpart="select callnaturegroup_id+'|'+callnaturegroupdescription as result  from callnaturegroup";
			}else if(usetype=='B0002') {//水务设施
				sqlpart="select callnature_id+'|'+callnaturedescription as result from callnature where callnaturegroup_id='"+pid+"' order by  CREATEDDATE";
			}else if(usetype=='B0003') {//投诉内容
				sqlpart="select callnature3_id+'|'+callnature3description as result from callnature3 where callnature_id='"+pid+"' order by  CREATEDDATE";
			}else if(usetype=='C0001') {//行政街道
				sqlpart="select code_id+'|'+Code_Name as result from c_codetables where Use_Type='街道'  and Use_Status=1 order by OrderNo";
			}
			log.debug("sqlpart结果" + sqlpart);

			def listcountresult =eliteBean.chaxun_sql(sqlpart,"dataSource");
			log.debug("查询结果" + listcountresult);
			def resultString = "";
			def str = "";
			int count=listcountresult.size();
			log.debug("count：" + count);
			if(count > 0) {
				for(int i=0;i<count;i++) {
					resultString  = listcountresult.get(i).get("result");
					log.debug("resultString：" + resultString);
					str=str+resultString+',';
				}
				str = str.substring(0,str.length() - 1);
			}
			JSONArray jsonArray1 = new JSONArray();
			// json对象
			JSONObject json = new JSONObject();
			json.put("key",str);

			jsonArray1.put(json);
						
			endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"获取的枚举值接口调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":"+jsonArray1.toString()+"}";
			
        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"获取的枚举值接口调用处理失败(" + e.getMessage() + ")\",\"data\":[]}";

        }
        return reJson;

    }
	
	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
			Rev_Value = String.valueOf(inJson.getDouble(getKey));
			} catch (Exception e1) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e2) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e3) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e4) {
						Rev_Value = "";
					}}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}
}